<template>
  <div>
    <template v-if="editing">
      <div class="m-t-10 flex align-items-end">
        <el-input v-model="title" placeholder="请输入资源标题" style="width: 20rem;" />
        <div class="flex align-items-center">
          <el-button
            type="primary"
            size="small"
            class="m-l-10"
            @click="saveTitle"
            :loading="loading"
          >保存编辑</el-button>
          <span @click="cancelEdit" class="el-link el-link--info m-l-10">取消</span>
        </div>
      </div>
      <div class="info f-mini m-b-8">提示：重命名无须带文件后缀</div>
    </template>
    <template v-else>
      <h2 class="flex align-items-end">
        <el-image v-if="curDoc.img" :src="uploadIcon(curDoc.img)" class="s20 m-r-10" />
        <template v-if="curDoc.good">
          <el-tag type="danger" size="small" disable-transitions class="m-r-10">精</el-tag>
        </template>
        <span :class="{ 'good-resource-text': curDoc.good }">{{ curDoc.title }}</span>
      </h2>
    </template>
  </div>
</template>

<script>
import { mapState, mapActions, mapGetters } from 'vuex';
import FileIconMixin from '@/utils/file-icon-mixin';

export default {
  name: 'edit-title',
  mixins: [FileIconMixin],
  props: {
    editing: Boolean,
  },
  computed: {
    ...mapState({
      curUser: 'currentUser',
      curDoc: 'currentDocument',
      curSpace: 'currentSpace',
    }),
    ...mapGetters(['isWebAdmin', 'isSpaceOwner', 'isSpaceAdmin']),
  },
  data() {
    return {
      title: '',
      loading: false,
    };
  },
  methods: {
    ...mapActions({ setCurDoc: 'setCurrentDocument' }),
    cancelEdit() { this.$emit('update:editing', false); },
    // 保存编辑
    saveTitle() {
      this.loading = true;
      this.$api.spaceContributions.create({
        action: 'update',
        spaceId: this.$route.params.spaceId,
        oldDocId: this.curDoc.id,
        title: `修改了《${this.curDoc.title}》的标题`,
        resources: [{
          class_type: 'ProductLocalFile',
          title: this.title,
          tag_titles: this.curDoc.tags,
        }],
      }).then((res) => {
        this.$message.success('提交成功');
        if (this.curSpace.autoAccept || this.isSpaceOwner || this.isSpaceAdmin || this.isWebAdmin) {
          const doc = Object.assign({}, this.curDoc, { title: this.title });
          this.setCurDoc(doc);
          this.$emit('update:editing', false);
        } else this.$router.push(`/spaces/${this.curSpace.id}/contributions/${res.data.id}`);
      }).catch(() => {})
        .then(() => { this.loading = false; });
    },
  },
  watch: {
    editing(val) { if (val) this.title = JSON.parse(JSON.stringify(this.curDoc)).title; },
  },
};
</script>

<style></style>
